namespace Crux.Core.Dapper;

/// <summary>
/// 
/// </summary>
public abstract class DapperContext : IDisposableObservable
{
    /// <summary>
    /// 
    /// </summary>
    public IDbConnection Connection { get; init; }
    /// <summary>
    /// 
    /// </summary>
    public IDbTransaction? Transaction { get; private set; }

    /// <summary>
    /// 
    /// </summary>
    public bool IsDisposed { get; private set; }
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
    private DapperContext()
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
    {

    }
    /// <summary>
    /// 
    /// </summary>
    public DapperContext(IDbConnection connection)
    {
        this.Connection = connection
            ?? throw new ArgumentNullException(nameof(connection));
    }

    internal IDbTransaction BeginTransaction()
    {
        return this.Transaction = this.Connection.BeginTransaction();
    }

    internal IDbTransaction BeginTransaction(IsolationLevel isolationLevel)
    {
        return this.Transaction = Connection.BeginTransaction(isolationLevel);
    }

    /// <summary>
    /// 
    /// </summary>
    public void Dispose()
    {
        if (this.IsDisposed)
        {
            return;
        }

        this.IsDisposed = true;

        {
            using var _ = this.Connection;
        }
        {
            using var _ = this.Transaction;
        }

        GC.SuppressFinalize(this);
    }
}